<template>
  <main>
    <div class="S">
      <li id="home">回到首页</li>
      <li id="user">
        <div class="userL" v-if="isLogin == false">
          <div>登录使用全部功能</div>
        </div>
        <div class="topAU" v-if="isLogin == true">
          <div class="userMsg" @click="thisUser">
            <li id="userA">
              <img :src="this.$store.state.userData.userAvatar" alt="" />
            </li>
            <li>你好,{{ this.$store.state.userData.userName }}</li>
          </div>
        </div>
      </li>
    </div>
    <div class="top A">
      <img :src="this.thisBook.avatar" alt="404" />
      <div class="A1">
        <li>{{ this.thisBook.bookname }}</li>
        <li id="explain">{{ this.thisBook.explain }}</li>
        <li>
          <el-button icon="el-icon-reading" @click="readbook(thisBook._id)"
            >阅读</el-button
          >
          <!-- <el-button icon="el-icon-reading" disabled v-if="this.thisBook.state == ">封禁中</el-button> -->
          <el-button
            icon="el-icon-star-off"
            v-if="isShou == false"
            @click="addshou"
            >收藏</el-button
          >
          <el-button
            icon="el-icon-star-on"
            v-if="isShou == true"
            @click="removeshou"
            >已收藏</el-button
          >
        </li>
      </div>
    </div>
    <div class="top B">
      <div class="B1">
        <li @click="getMsg"><a href="javascript:;">作品相关</a></li>
        <li @click="getMuLu"><a href="javascript:;">作品目录</a></li>
      </div>
    </div>
    <div class="top C">
      <!-- 信息 -->
      <div v-if="isMsg == true">
        <el-card id="CMa">
          <img :src="writerImg" alt="404" />
          <el-button
            type="text"
            @click="toWriter(thisBook.writerid)"
            class="CMaN"
            >{{ this.thisBook.writername }}</el-button
          >
        </el-card>
        <el-card id="CMb">
          <textarea
            name=""
            cols="90"
            rows="6"
            maxlength="240"
            v-model="pingLun"
          ></textarea>
          <el-button type="primary" @click="upPingLun" v-if="isLogin == true"
            >发<br />表<br />评<br />论</el-button
          >
          <el-button type="primary" v-if="isLogin == false" disabled
            >请<br />先<br />登<br />录</el-button
          >
        </el-card>
        <el-card id="allPing" shadow="never">
          <li v-for="(item, i) in thisTopPing" :key="i" id="A">
            <div id="AA">
              <img :src="item.userava" alt="404" />
              <div id="pingMain">
                <h4 id="hui" @click="touser(item.userid)">
                  {{ item.username }}
                </h4>
                <p>{{ item.text }}</p>
                <li>
                  <h6>{{ item.date|date }}</h6>
                  <span id="hui" @click="openHui(item._id, item.username)"
                    >回复</span
                  >
                  <span
                    id="hui"
                    @click="getChildPing(item._id)"
                    v-if="item._id != childPingTopId"
                    >展开评论</span
                  >
                  <span
                    v-if="item._id == childPingTopId"
                    id="hui"
                    @click="closeChildPing"
                    >收起</span
                  >
                  <span
                    id="hui"
                    v-if="item.userid == thisUserId"
                    @dblclick="removeTopPing(item._id, item.beforeid)"
                    @click="removePing(item._id, item.beforeid)"
                    >删除</span
                  >
                  <span id="hui" v-if="item.userid != thisUserId">举报</span>
                </li>
              </div>
            </div>
            <div v-if="item._id == childPingTopId" class="child">
              <div id="AA" v-for="(items, i) in childrenPing" :key="i">
                <span v-if="items == null">暂无评论</span>
                <img :src="items.userava" alt="404" />
                <div id="pingMain">
                  <h4 id="hui" @click="touser(items.userid)">
                    {{ items.username }}
                  </h4>
                  <p>{{ items.text }}</p>
                  <li>
                    <h6>{{ items.date | date }}</h6>
                    <span id="hui" @click="openHui(item._id, items.username)"
                      >回复</span
                    >
                    <span
                      id="hui"
                      v-if="items.userid == thisUserId"
                      @click="removePing(items._id, items.beforeid)"
                      >删除</span
                    >
                    <span id="hui" v-if="items.userid != thisUserId">举报</span>
                  </li>
                </div>
              </div>
              <div class="block"></div>
              <span class="demonstration">共有{{ isLengthC }}条记录</span>
              <el-pagination
                style="display: block"
                @current-change="handleCurrentChangeC"
                :current-page.sync="currentPageC"
                layout="prev, pager, next"
                :page-size="8"
                :total="isLengthC"
              >
              </el-pagination>
            </div>
            <div id="reply" v-if="inPing == item._id">
              <textarea id="HuiFu" rows="5" maxlength="240"></textarea>
              <li>
                <el-button @click="subHui(item._id)">发送</el-button>
                <el-button @click="cancelHui">取消</el-button>
              </li>
            </div>
          </li>
        </el-card>
        <!-- 分页 -->
        <div class="block">
          <span class="demonstration">共有{{ isLength }}条记录</span>
          <el-pagination
            style="display: block"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            layout="prev, pager, next, jumper"
            :page-size="10"
            :total="isLength"
          >
          </el-pagination>
        </div>
      </div>
      <!-- 章节 -->
      <div v-if="isMsg == false" class="title">
        <li v-for="(item,i) in titles" :key="i" @click="readBookByTitle(i)">
          <span>{{item.title}}</span>
          </li>
      </div>
    </div>
    <div class="top D">
      <textarea id="ju" cols="30" rows="3" style="resize: none;" maxlength="20" v-model="jubao">输入举报理由</textarea>
      <button id="subju" @click="subJuBao">举报</button>
    </div>
  </main>
</template>

<script>
export default {
  created() {
    if (window.sessionStorage.getItem("userName") != null) {
      this.isLogin = true;
      this.isShouCang();
      this.thisUserId = window.sessionStorage.getItem("userId");
    }
    this.getThisBook();
    this.getTopPing();
  },
  data() {
    return {
      jubao:"",
      childPingTopId: -1,
      thisUserId: -1,
      inPing: -1,
      isLogin: false,
      //userId: null,
      thisBook: {},
      isMsg: true,
      writerImg: "",
      pingLun: "",
      isShou: false,
      bookcase: [],
      inHei: false,
      thisTopPing: [],
      childrenPing: [],
      titles:[],
      isLength: 0,
      currentPage: 1,
      pageSize: 10,
      isLengthC: 0,
      currentPageC: 1,
      pageSizeC: 10,
    };
  },
  methods: {
    //路由
    thisUser() {
      let routeUrl = this.$router.resolve(
        `/thisUser/${window.sessionStorage.getItem("userId")}`
      );
      window.open(routeUrl.href, "_blank");
    },
    readbook(id) {
      let routeUrl = this.$router.resolve(`/readbook/${id}/${0}`);
      window.open(routeUrl.href, "_blank");
    },
    toWriter(id) {
      //console.log(id);
      let routeUrl = this.$router.resolve(`/toWriter/${id}`);
      window.open(routeUrl.href, "_blank");
    },
    async touser(id) {
      //console.log(id);
      const {data:res} =await this.$http.get(`/ping/identity/${id}`)
      if(res.data == 1){
        let routeUrl = this.$router.resolve(`/touser/${id}`);
        window.open(routeUrl.href, "_blank");
        return
      } if(res.data == 2){
        this.toWriter(id)
        return
      } else {
        this.$message.error("该用户已注销")
      }
        //console.log(res);
      // let routeUrl = this.$router.resolve(`/touser/${id}`);
      // window.open(routeUrl.href, "_blank");
    },
    readBookByTitle(i){
      //console.log(i);
      let routeUrl = this.$router.resolve(`/readbook/${this.$route.params.id}/${i}`)
      window.open(routeUrl.href, "_blank");
    },
    //函数
    async getWriterImg() {
      const { data: res } = await this.$http.get(
        `writers/getAva/${this.thisBook.writerid}`
      );
      this.writerImg = res.data.avatar;
    },
    //获得本书相关信息
    async getThisBook() {
      //console.log(this.$route.params.id);
      const { data: res } = await this.$http.get(
        `books/thisbook/${this.$route.params.id}`
      );

      if (res.status != 200) {
        return this.$message.error("获取失败");
      } else {
        //console.log(res);
        this.thisBook = res.data;
        //console.log(res.data);
        this.getWriterImg();
        this.isHei();
      }
    },
    //
    //是否搜藏
    async isShouCang() {
      const { data: res } = await this.$http.post(
        `/users/isInShuJia/${window.sessionStorage.getItem("userId")}`,
        {
          bookid: this.$route.params.id,
        }
      );
      if (res == "OK") {
        this.isShou = true;
      } else {
        this.isShou = false;
      }
    },
    //用户是否在黑名单中
    isHei() {
      if (this.thisBook.hei.includes(window.sessionStorage.getItem("userId"))) {
        this.isHei = true;
      }
    },
    getMsg() {
      this.isMsg = true;
      this.getTopPing();
    },
    async getMuLu() {
      this.isMsg = false;
        const{data:res} =await this.$http.get(`/books/readTitle/${this.$route.params.id}`);
        if(res.status == 200 ){
          this.titles = res.data;
        }
    },
    //发表评论
    async upPingLun() {
      let sendPing = this.pingLun.trim();
      if (sendPing.length > 0) {
        if (this.isHei && window.sessionStorage.getItem("userState") == 1) {
          const { data: res } = await this.$http.post(
            `/ping/addnew/${window.sessionStorage.getItem("userId")}`,
            {
              bookid: this.$route.params.id,
              writerid: this.thisBook.writerid,
              text: sendPing,
              ava: window.localStorage.getItem("userAvatar"),
              name: window.sessionStorage.getItem("userName"),
            }
          );
          if (res == "OK") {
            this.pingLun = "";
            this.getTopPing();
          }
        } else {
          this.$message.error("用户在黑名单中或为封禁状态");
        }
      } else {
        this.$message.error("评论内容不能为空");
      }
      //console.log(this.pingLun);
      //console.log(this.thisBook._id);
    },
    async addshou() {
      if (this.isLogin) {
        const { data: res } = await this.$http.post(
          `/users/addSoucang/${window.sessionStorage.getItem("userId")}`,
          {
            bookid: this.$route.params.id,
          }
        );
        // console.log(res);
        this.isShouCang();
      } else {
        this.$message.success("请先登录");
      }
    },
    async removeshou() {
      const { data: res } = await this.$http.post(
        `/users/removeShoucang/${window.sessionStorage.getItem("userId")}`,
        {
          bookid: this.$route.params.id,
        }
      );
      this.isShouCang();
    },
    //获取顶级评论
    async getTopPing() {
      const {
        data: res,
      } = await this.$http.post(
        `/ping/getTopByBookid/${this.$route.params.id}`,
        { pageSize: this.pageSize, currentPage: this.currentPage }
      );
      if (res.status == 200) {
        this.thisTopPing = res.data;
        this.isLength = res.num;
      } else {
        this.$message.erro("获取评论失败");
      }
    },
    openHui(id, name) {
      //console.log(id);
      if(this.isLogin){
        this.inPing = id;
      this.$nextTick(() => {
        document.getElementById("HuiFu").placeholder = `@${name}：`;
        document.getElementById("HuiFu").focus();
      });
      return
      }
      else {
        this.$message.error("未登录")
      }
      
    },
    cancelHui() {
      this.inPing = -1;
    },
    async subHui(id) {
      let a = document.getElementById("HuiFu").placeholder;
      let b = document.getElementById("HuiFu").value;
      let c = a + b;
    
      if (a.length > 1 && b.length > 1) {
        if (this.isHei && window.sessionStorage.getItem("userState") == 1) {
          const { data: res } = await this.$http.post(
            `/ping/secHuiFu/${window.sessionStorage.getItem("userId")}`,
            {
              bookid: this.$route.params.id,
              writerid: this.thisBook.writerid,
              beforeid: id,
              text: c,
              ava: window.localStorage.getItem("userAvatar"),
              name: window.sessionStorage.getItem("userName"),
            }
          );
          if (res == "OK") {
            this.inPing = -1;
            document.getElementById("HuiFu").value = "";
            this.getChildPing(id);
          }
        } else {
          this.$message.error("用户在黑名单中或为封禁状态");
        }
      } else {
        this.$message, error("内容太短");
      }
    },
    async getChildPing(id) {
      this.childPingTopId = id;
      const { data: res } = await this.$http.get(`/ping/getChildByTopId/${id}`,
       { pageSize: this.pageSizeC, currentPage: this.currentPageC });
      this.childrenPing = res.data;
      this.isLengthC = res.num;
      //console.log(res);
    },
    closeChildPing() {
      this.childPingTopId = -1;
    },
    //删除子plun
    async removePing(id, before) {
      if (before == 0) {
        this.$message.error(
          "删除此评论将删除此评论下所有评论，如想删除请双击删除键"
        );
      } else {
        const { data: res } = await this.$http.delete(
          `/ping/deletePing/${id}`,
          { beforeid: before }
        );
        if (res == "OK") {
          this.getChildPing(before);
        }
        //console.log(res);
      }
    },
    //删除父pinglun
    async removeTopPing(id, before) {
      const { data: res } = await this.$http.delete(
          `/ping/deletePing/${id}`,
          { beforeid: before }
        );
        if (res == "OK") {
          this.getTopPing();
        }
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getTopPing();
    },
    handleCurrentChangeC(val) {
      this.currentPageC = val;
      this.getChildPing();
    },
    async subJuBao(){
      if(this.jubao == ''){
        return this.$message.error('请先输入举报理由')
      }
      const {data:res} = await this.$http.post(`/users/jubao/${window.sessionStorage.getItem("userId")}`,{bookid:this.$route.params.id,reason:this.jubao});
      if (res == 'OK') {
        this.jubao = '';
        return this.$message.success('举报成功')
      }
    }
  },
};
</script>

<style lang="less" scoped>
//li 样式
li {
  display: flex;
  list-style: none;
}
//主体盒子
main {
  min-height: 2800px;
  width: 100%;
  background-color: rgb(243, 252, 233);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  flex: 100;
}
//主体下顶级盒子
.top {
  display: flex;
  width: 70%;
}
//导航横栏
.S {
  flex: 2;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: rgb(110, 109, 109);
  font-size: 24px;
  color: white;
}
.S #home:hover {
  background-color: black;
  cursor: pointer;
}
.S li:nth-child(1) {
  height: 100%;
  width: 120px;
  margin-left: 15px;
  justify-content: center;
  align-items: center;
}
.userMsg:hover {
  color: red;
  cursor: pointer;
}
#user {
  display: flex;
  flex-direction: row;
}
#userA {
  width: 50px;
  margin-right: 9px;
}
.userL {
  display: flex;
  margin-right: 30px;
}
.userL div {
  display: flex;
  margin-right: 5px;
  margin-left: 5px;
}
.userMsg img {
  height: 50px;
  width: 50px;
}
.userMsg {
  display: flex;
  align-items: center;
  margin-right: 5px;
  margin-left: 5px;
}
.topAU {
  display: flex;
  align-items: center;
  margin-right: 40px;
}
.A {
  height: 307px;
  //flex: 12;
  display: flex;
  align-items: center;
  border-style: solid;
  border-width: 1px 1px 0px 1px;
  border-color: rgba(175, 172, 172, 0.8);
  background-color: white;
}
.A img {
  width: 169px;
  height: 192px;
  margin: 25px;
}
.A img:hover {
  width: 175px;
  height: 200px;
  box-shadow: 0px 0px 10px rgb(37, 36, 36);
}
.A1 {
  display: flex;
  height: 100%;
  width: 100%;
  flex-direction: column;
  justify-content: space-between;
  background-color: #fff;
}
.A1 li:nth-child(1) {
  margin-top: 50px;
  font-size: 32px;
  font-weight: 800;
}
.A1 li:nth-child(2) {
  height: 110px;
  margin-left: 30px;
  font-size: 18px;
}
.A1 li:nth-child(3) {
  height: 70px;
  flex-direction: row-reverse;
  align-items: center;
  // background-color: black;
}
#explain {
  margin-right: 15px;
}
.A li .el-button {
  margin-left: 0px;
  margin-right: 15px;
  font-size: 20px;
  font-weight: 600;
}
.B {
  height: 40;
  background-color: white;
  font-size: 25px;
  font-weight: 550;
  align-items: center;
}
.B1 {
  display: flex;
  width: 100%;
  border-style: solid;
  border-width: 0px 0px 2px 0px;
  border-color: rgba(175, 172, 172, 0.5);
}
.B1 li:nth-child(1) {
  margin-left: 25px;
  margin-right: 18px;
}
a {
  text-decoration: none;
  color: black;
}
.C {
  flex: 75;
  background-color: #fff;
}
.C div {
  display: flex;
  height: 100%;
  width: 100%;
  flex-direction: column;
}
#CMa {
  display: flex;
  width: 100%;
  height: 140px;
  justify-content: center;
}
#CMa img {
  margin-left: 30px;
  margin-right: 20px;
  height: 75px;
  width: 75px;
}
.CMaN {
  position: relative;
  bottom: 60px;
  font-size: 22px;
  //top: 15px;
}
#CMb {
  //padding: 0px;
  //margin-bottom: 10px;
  margin-top: 15px;
  height: 180px;
  width: 100%;
  display: flex;
  align-items: center;
  font-size: 18px;
}
#CMb textarea {
  font-size: 18px;
  resize: none;
}
#CMb .el-button {
  position: relative;
  height: 132px;
  width: 60px;
  text-align: center;
  word-wrap: break-word;
  bottom: 87px;
  font-size: 18px;
}
#allPing {
  display: flex;
  height: 1740px;
  border-width: 0px;
  flex-direction: column;
}
#AA {
  display: flex;
  flex-direction: row;
}
#allPing #A {
  min-height: 140px;
  width: 100%;
  padding: 10px;
  align-items: center;
  flex-direction: column;
  border-style: solid;
  border-width: 0px 0px 1px 0px;
}
#allPing #A img {
  height: 90px;
  width: 90px;
}
#pingMain {
  margin-left: 15px;
  height: 100%;
  display: flex;
  flex-direction: column;
}
#pingMain h4 {
  margin-top: 10px;
  margin-bottom: 10px;
}
#pingMain p {
  margin-top: 5px;
  margin-left: 5px;
  margin-bottom: 5px;
  height: 70px;
}
#pingMain li {
  height: 28px;
  padding: 0px;
  justify-content: space-between;
}
#pingMain h6 {
  margin-bottom: 5px;
  margin-top: 5px;
}
#hui {
  margin-right: 40px;
}
#hui:hover {
  color: blue;
  cursor: pointer;
}
#reply {
  display: flex;
  height: 120px;
  width: 100%;
}
#reply .el-button {
  width: 100px;
  margin-right: 15px;
}
#HuiFu {
  width: 95%;
  font-size: 18px;
  resize: none;
}
.child #AA {
  width: 94%;
  margin-left: 6%;
}
.block {
  display: block;
}
.title{
  display: flex;
  //min-height: 2200px;
  flex-wrap: wrap;
  flex-direction: row !important;
  font-size: 20px;
}
.title li{
  justify-content: center;
  align-items: center;
  width: 33%;
  height: 40px;
  border-style: dashed;
  border-width: 0px 0px 1px 0px;
}
.title li span:hover{
  color: red;
  cursor: pointer;
}
.D {
  background-color: rgb(245, 195, 210);
  height: 200px;
}
#ju{
  font-size: 18px;
  height: 50px;
}
#subju{
  font-size: 18px;
  height: 56px;
}
</style>
